#!/usr/bin/env python
# Copyright (c) 2009 GHCM Ltd. All rights reserved.

from __future__ import print_function
from __future__ import unicode_literals

from PyQt4.QtCore import (Qt,QVariant,QString,QTimer)
from PyQt4.QtGui import (QDialog,QTableWidget,QTableWidgetItem)

if __name__ == "__main__":
    from mlhmb import lib
    class FLOW(object):
        def __init__(self,**kwargs):
            self.REdatafact     = False
            self.REsvm          = False
            self.REmstat        = False
            self.__dict__.update(kwargs)
from minings.clustering.kmeans import kmeans
from minings.utils import mysqlrecord
from mlhmb.minings.clustering.kmeans.widgets import ui_kmeans

import orange,cPickle
from interval import Interval

DSET = range(1)[0]


class KMEANSDialog(QDialog, ui_kmeans.Ui_KMEANSDialog):

    def __init__(self, parent = None):
        super(KMEANSDialog, self).__init__(parent)
        self.setupUi(self)
        self.R              = mysqlrecord.datasetMySQLrecord(databasename = "gut")
        self.headers        = ["Dataset Name"]
        QTimer.singleShot(100,self.updateTable)
    def loadData(self):
        #MySQL properties for the results
        try:
            self.R.cursor.execute("use %s" % self.R.mainDBname)
        except:
            print("Database %s does not exist, abort .." % self.R.mainDBname)
            return False
        try:
            self.R.cursor.execute("desc %s" % self.R.tab_res.tname)
        except:
            print("Table %s of %s does not exist, abort .." % (self.R.tab_res.tname,self.R.mainDBname))
            return False
        #Initial Running
#        self.R.cursor.execute("""select * from %s""" % self.R.tab_res.tname)
#        row = self.R.cursor.fetchall()
#        self.R.cursor.execute("""select * from %s where %s="%s" 
#                              """ % (self.R.tab_res.tname       ,
#                                     self.R.tab_res.datasetname ,
#                                     "gut_Endo_Colon2__Healthy Control__Ulcerative Colitis" ))
#        row = self.R.cursor.fetchone()
        row = True
        if row == None:
            return False
        else:
#            self.d              = {}
#            datasetname         = row[self.R.tab_res.datasetname]
#            F                   = cPickle.loads(row[self.R.tab_res.datafact])
#            results_svm         = cPickle.loads(row[self.R.tab_res.results_svm])
#            results_mstat       = cPickle.loads(row[self.R.tab_res.results_mstat])
#            self.d[datasetname] = (F,results_svm,results_mstat)
            
#            self.d = {}
#            for i in row:
#                datasetname         = i[self.R.tab_res.datasetname]
#                F                   = cPickle.loads(i[self.R.tab_res.datafact])
#                results_svm         = cPickle.loads(i[self.R.tab_res.results_svm])
#                results_mstat       = cPickle.loads(i[self.R.tab_res.results_mstat])
#                self.d[datasetname] = (F,results_svm,results_mstat)
            
            self.d              = {}
            self.d["Iris"]      = None
            
            self.dsort          = self.d.keys()
            self.dsort.sort()
            self.dsort_item     = [QTableWidgetItem(QString(u)) for u in self.dsort]
            return True
    def updateTable(self):
        if self.loadData():
            table = self.dsetTableWidget
            table.clear()
            tableHeaderView     = table.verticalHeader()
            tableHeaderView.hide()
            table.setSortingEnabled(False)
            table.setRowCount(len(self.dsort))
            table.setColumnCount(len(self.headers))
            table.setHorizontalHeaderLabels(self.headers)
            table.setAlternatingRowColors(True)
            table.setEditTriggers(QTableWidget.NoEditTriggers)
            table.setSelectionBehavior(QTableWidget.SelectRows)
            table.setSelectionMode(QTableWidget.SingleSelection)
            for row,item in enumerate(self.dsort_item):
                item.setData(Qt.CheckStateRole,QVariant(Qt.Unchecked)) 
                table.setItem(row,DSET,item)
            table.horizontalHeader().setStretchLastSection(True)
    def doKmeans(self):
        #Get dataset checked
        dsetChecked = []
        for row in range(self.dsetTableWidget.rowCount()):
            item            = self.dsetTableWidget.item(row,0)
            itemdata        = item.data(Qt.CheckStateRole) #Return QVariant
            check,ok        = itemdata.toInt() #Return check state and the flag
            if check == Qt.Checked:
                datasetname = str(item.text())
                dsetChecked.append(datasetname) 
        for i in dsetChecked:
            datasetname     = i
#            results_svm     = self.d[i][1]
#            results_mstat   = self.d[i][2]
#            #Get SVM orange data
#            datasvm         = results_svm.results[0].SVMtraining_data
#            #Get MSTAT orange data
#            mres            = results_mstat.orgnresult
#            mdata           = mres.data
#            mattrs          = mdata.domain.attributes
#            mclassVar       = mdata.domain.classVar
#            mpf             = mres.MSTATp_fisher
#            mpf_selected    = [u for u in mpf if \
#                               mpf[u] in Interval(0,0.05,
#                                                  lower_closed = False,
#                                                  upper_closed = True) ]
#            mstatAttrs      = [u for u in list(mattrs) if u.name in mpf_selected]
#            if mstatAttrs != []:
#                mstatAttrs.sort(lambda x,y: cmp(x.name,y.name))
#                newmdomain      = orange.Domain(mstatAttrs + [mclassVar])
#                datamstat       = mdata.select(newmdomain)
#            else:
#                datamstat       = None

#            datasvm.save("C:\Downloads\svm.tab")
#            datamstat.save("C:\Downloads\m.tab")
#            self.somProgressBar.setValue(100)

            #Run SOM for each dataset
#            print("here")
#            print(datasetname)
#            netSVM          = reald.TR(data = datasvm, datasetname = datasetname)
#            netSVM.train()
#            netSVM.doUmatrix("svm")
#            if datamstat != None:
#                netMSTAT        = reald.TR(data = datamstat, datasetname = datasetname)
#                netMSTAT.train()
#                netMSTAT.doUmatrix("mstat")
            
            testfile    = "C:\\Users\\aonlazio\\Desktop\\BILLION\\PLATFORM\\code\\ghcm\\mlhmb\\information\\dataset\\example_datasets\\iris.tab"
            datatest    = orange.ExampleTable(testfile)
            k           = kmeans.KMEANS(data = datatest)
        
if __name__ == "__main__":
    import sys
    from PyQt4.QtGui import QApplication
    app         = QApplication(sys.argv)
    form        = KMEANSDialog()
    form.show()
    sys.exit(app.exec_()) 

